package com.chuangan.releasetask.Utils;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
 * @Author: zihua
 * @Date: 2020/8/13 16:11
 * @Version 1.0
 */
public class QuartzUtils {


    public static void quartzConfig(String jobName,String jobGroup,JobDataMap jobDataMap,String triggerName,String triggerGroup,String task) throws Exception {
        Class cls = Class.forName(task);
        Date executeDate = (Date) jobDataMap.get("executeDate");
        String cron = DateUtils.getCron(executeDate);
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.clear();
        // 启动scheduler
        scheduler.start();
        // 创建TaskJob的JobDetail实例，并设置name/group
        JobDetail jobDetail = JobBuilder.newJob(cls)
                .withIdentity(jobName,jobGroup)
                //JobDataMap可以给任务传递参数
                //.usingJobData("jobPara",jobPara)
                .usingJobData(jobDataMap)
                .build();



        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerName,triggerGroup)
                // trigger 参数
                //.usingJobData("job_trigger_param","job_trigger_param1")
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                 //       .withMisfireHandlingInstructionDoNothing())
                //.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2018"))
                .build();
        // 注册JobDetail实例到scheduler以及使用对应的Trigger触发时机
        try {
            scheduler.scheduleJob(jobDetail,trigger);
        } catch (SchedulerException e) {
            System.out.println(jobName + "定时任务时间已过期");
            e.printStackTrace();
        }
    }



}
